package com.zhaolixiang.slidetabview

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import java.util.jar.Attributes
import android.widget.Scroller
import android.support.v4.view.ViewConfigurationCompat
import android.view.ViewConfiguration





/**
 * Created by Administrator on 2018/1/3.
 */
class SlideTabLinearLayout2 :ViewGroup {
    /**
     * 用于完成滚动操作的实例
     */
    private  var mScroller: Scroller = Scroller(context)

    /**
     * 判定为拖动的最小移动像素数
     */
    private var mTouchSlop: Int = 0

    /**
     * 手机按下时的屏幕坐标
     */
    private var mXDown: Float = 0f

    /**
     * 手机当时所处的屏幕坐标
     */
    private var mXMove: Float = 0f

    /**
     * 上次触发ACTION_MOVE事件时的屏幕坐标
     */
    private var mXLastMove: Float = 0f
    /**
     * 界面可滚动的左边界
     */
    private var leftBorder: Int = 0

    /**
     * 界面可滚动的右边界
     */
    private var rightBorder: Int = 0
    init {
        // 第一步，创建Scroller的实例
        val configuration = ViewConfiguration.get(context)
        // 获取TouchSlop值
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        Log.e("测量了","widthMeasureSpec：$widthMeasureSpec---heightMeasureSpec$heightMeasureSpec")
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val childCount=this.childCount
        var width=0;
        if(childCount>0){
            for(i in 0 until childCount){
                val child=this.getChildAt(i)
                measureChild(child,widthMeasureSpec,heightMeasureSpec)
                width+= child.measuredWidth
                Log.e("测量了"," child.measuredWidth：${child.measuredWidth}")
            }
            Log.e("测量了"," child.measuredWidth：${width}")
        }
        setMeasuredDimension(width,heightMeasureSpec)
        //super.onMeasure(width, heightMeasureSpec)

    }
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        if (changed) {
            val childCount = childCount
            for (i in 0 until childCount) {
                val childView = getChildAt(i)
                // 为ScrollerLayout中的每一个子控件在水平方向上进行布局
                childView.layout(i * childView.measuredWidth, 0, (i + 1) * childView.measuredWidth, childView.measuredHeight)
            }
            // 初始化左右边界值
            leftBorder = getChildAt(0).left
            rightBorder = getChildAt(getChildCount() - 1).right
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.e("触摸按下了","ACTION_DOWN"+ev.x)
                mXDown = ev.rawX
                mXLastMove = mXDown
            }
            MotionEvent.ACTION_MOVE -> {
                Log.e("触摸移动了","ACTION_DOWN"+ev.x)
                mXMove = ev.rawX
                val diff = Math.abs(mXMove - mXDown)
                mXLastMove = mXMove
                // 当手指拖动值大于TouchSlop值时，认为应该进行滚动，拦截子控件的事件
                if (diff > mTouchSlop) {
                    return true
                }
            }
        }
        return super.onInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN->{
                //按下了
                Log.e("按下了","ACTION_DOWN"+event.x)
            }
            MotionEvent.ACTION_MOVE -> {
                Log.e("移动了","ACTION_MOVE")
                //本次坐标值
                mXMove = event.rawX
                Log.e("移动了1","mXMove:$mXMove")
                //移动的距离差值
                val scrolledX = (mXLastMove - mXMove).toInt()
                Log.e("移动了2","scrolledX：$scrolledX")
                /*if (scrollX + scrolledX < leftBorder) {
                    Log.e("移动了3","leftBorder:$leftBorder")
                    scrollTo(leftBorder, 0)
                    return true
                } else if (scrollX + width + scrolledX > rightBorder) {
                    Log.e("移动了4","rightBorder - width：${rightBorder - width}")
                    scrollTo(rightBorder - width, 0)
                    return true
                }*/
                Log.e("移动了5","scrolledX:$scrolledX")
                scrollBy(scrolledX, 0)
               // mScroller.startScroll(scrollX, 0, dx, 0)
                mXLastMove = mXMove
            }
            MotionEvent.ACTION_UP -> {
                Log.e("手指拿开了","当手指抬起时，根据当前的滚动值来判定应该滚动到哪个子控件的界面")
                // 当手指抬起时，根据当前的滚动值来判定应该滚动到哪个子控件的界面
                val targetIndex = (scrollX + width / 2) / width

                val dx = targetIndex * width - scrollX
                Log.e("手指拿开了1","width:$width---dx：$dx");
                // 第二步，调用startScroll()方法来初始化滚动数据并刷新界面
                Log.e("手指拿开了","第二步，调用startScroll()方法来初始化滚动数据并刷新界面"+scrollX)
               // mScroller.startScroll(scrollX, 0, dx, 0)
                invalidate()
            }
        }
        return super.onTouchEvent(event)
    }
   /* override fun onTouchEvent(ev: MotionEvent): Boolean {
        when(ev.action){
            MotionEvent.ACTION_DOWN->{
                //按下了
                Log.e("按下了","ACTION_DOWN"+ev.x)
                previousX=ev.x
                return true
            }
            MotionEvent.ACTION_MOVE->{
                //移动了
                Log.e("移动了","ACTION_MOVE"+(ev.x-previousX)+"---"+ scrollX+"==="+scaleX)
                // move(ev.x-previousX)
                val curX=(ev.x-previousX)*1.1;
                if(Math.abs(curX)>5){
                    layout((left+curX).toInt(),top,(right+curX).toInt(),bottom)
                }
                previousX=ev.x

            }
        }
        return super.onTouchEvent(ev)
    }*/

    override fun computeScroll() {
        // 第三步，重写computeScroll()方法，并在其内部完成平滑滚动的逻辑
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY())
            invalidate()
        }
    }

    private var previousX=0f
    private var previousY=0f
    private lateinit var ll_zong:LinearLayout
    private var leftAndRightMinWidth=0
    constructor(context: Context):super(context)
    constructor(context: Context,attrs:AttributeSet):super(context,attrs)
    constructor(context: Context,attrs: AttributeSet,defStyleAttr:Int):super(context,attrs,defStyleAttr)


    //设置左右两边边至少剩余的宽度
    public fun setMinWidth(minWidth:Int){
        //1750
        Log.e("设置左边最少距离",""+minWidth)
        leftAndRightMinWidth=minWidth
    }



    override fun onScrollChanged(x: Int, y: Int, oldX: Int, oldY: Int) {
        Log.e("滑动了","onScrollChanged$x---$oldX")
        if(leftAndRightMinWidth>0){
            //只有当初始化后才有效果

            if(x<leftAndRightMinWidth){
                //如果向左滑动了，就重新添加一组数据到左边
               // leftAdd()
            }
        }
        super.onScrollChanged(x, y, oldX, oldY)
    }

    private fun leftAdd(){
        for(x in 0 until 3){
            val ll_zong:LinearLayout=this.getChildAt(0) as LinearLayout
            val tv= TextView(this.context)
            tv.text="我是新增加的文本"+x
            tv.textSize=48f
            ll_zong.addView(tv,0)
            Log.e("leftAdd","我是新增加的文本"+x)
        }
    }

    private fun move(moveX:Float){
        Log.e("移动距离", "moveX：$moveX")
        val objectAnimatorX=ObjectAnimator.ofFloat(this,"translationX",moveX)
        objectAnimatorX.start()

    }


}